package com.bawei.search

import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.search.adapter.KeyWordListAdapter
import com.bawei.search.adapter.SearchVideoListAdapter
import com.bawei.search.databinding.ActivitySearchBinding
import com.bawei.search.intent.SearchViewIntent
import com.bawei.search.state.SearchUiState
import com.bawei.search.vm.SearchViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RoutePath.PATH_SEARCH_PAGE)
@AndroidEntryPoint
class SearchActivity : BaseMviActivity<ActivitySearchBinding>() {

    private val mViewModel: SearchViewModel by viewModels()

    private lateinit var mVideoListAdapter: SearchVideoListAdapter
    private lateinit var mHotListAdapter: KeyWordListAdapter
    private lateinit var mHistoryListAdapter: KeyWordListAdapter

    private var mVideoList = mutableListOf<SimpleVideoEntity>()
    private var mHotList = mutableListOf("视频", "青年", "都市视频", "娱乐", "八维青年", "创意AI视频", "娱乐", "青年", "都市视频", "娱乐", "青年", "都市视频", "娱乐")
    private var mHistoryList = mutableListOf<String>()



    @Autowired
    @JvmField
    var keyWords: String = ""

    private var tempSearchKeyword: String = ""

    private var pageIndex: Int = 1
    private var pageSize: Int = 10

    override fun getLayoutId(): Int = R.layout.activity_search

    override fun initViews() {
        ARouter.getInstance().inject(this)

        //页面返回事件
        mDataBinding.ivBack.setOnClickListener {
            this@SearchActivity.finish()
        }

        //视频列表
        mDataBinding.rvList.layoutManager = LinearLayoutManager(this@SearchActivity, LinearLayoutManager.VERTICAL, false)
        mVideoListAdapter = SearchVideoListAdapter(mVideoList)
        mDataBinding.rvList.adapter = mVideoListAdapter

        //搜索热词
        mDataBinding.rvHotList.layoutManager = FlexboxLayoutManager(this@SearchActivity).apply {
            flexDirection = FlexDirection.ROW
            flexWrap = FlexWrap.WRAP
            justifyContent = JustifyContent.FLEX_START
        }
        mHotListAdapter = KeyWordListAdapter(mHotList)
        mHotListAdapter.setOnItemClickListener(object : KeyWordListAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {
                mDataBinding.cltSearchKeywords.visibility = View.INVISIBLE
                mDataBinding.rvList.visibility = View.VISIBLE
                loadVideoByNewKeyword(mHotList[position])

            }
        })
        mDataBinding.rvHotList.adapter = mHotListAdapter

        //搜索历史记录
        mDataBinding.rvHistoryList.layoutManager = FlexboxLayoutManager(this@SearchActivity).apply {
            flexDirection = FlexDirection.ROW
            flexWrap = FlexWrap.WRAP
            justifyContent = JustifyContent.FLEX_START
        }
        mHistoryListAdapter = KeyWordListAdapter(mHistoryList)
        mHistoryListAdapter.setOnItemClickListener(object : KeyWordListAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {
                mDataBinding.cltSearchKeywords.visibility = View.INVISIBLE
                mDataBinding.rvList.visibility = View.VISIBLE
                loadVideoByNewKeyword(mHistoryList[position])
            }
        })
        mDataBinding.rvHistoryList.adapter = mHistoryListAdapter

        //搜索框文本事件监听
        mDataBinding.svKeywords.setOnQueryTextListener(object : SearchView.OnQueryTextListener{

            override fun onQueryTextSubmit(query: String?): Boolean {
                if (!query.isNullOrEmpty()){
                    mDataBinding.cltSearchKeywords.visibility = View.INVISIBLE
                    mDataBinding.rvList.visibility = View.VISIBLE
                    loadVideoByNewKeyword(query)
                }
               return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (newText.isNullOrEmpty()) {
                    mDataBinding.cltSearchKeywords.visibility = View.INVISIBLE
                    mDataBinding.rvList.visibility = View.VISIBLE
                } else {
                    mDataBinding.cltSearchKeywords.visibility = View.VISIBLE
                    mDataBinding.rvList.visibility = View.INVISIBLE
                }

                return false
            }

        })

        //设置点击事件
        mVideoListAdapter.setOnItemClickListener(object : SearchVideoListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.iv_video_play -> {

                    }
                    R.id.iv_commend -> {

                    }

                    R.id.iv_more -> {

                    }
                }
            }
        })





    }

    private fun loadVideoByNewKeyword(keyword: String){
        //临时缓存一下关键词
        tempSearchKeyword = keyword
        //清空输入内容
        mDataBinding.svKeywords.setQuery("", false)
        //清理输入框焦点，关闭键盘
        mDataBinding.svKeywords.clearFocus()
        //发起数据请求
        lifecycleScope.launch {
            mViewModel.channel.send(SearchViewIntent.LoadSimpleVideoListByKeyword(keyword, pageIndex, pageSize))
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(SearchViewIntent.LoadSimpleVideoListByKeyword(this.keyWords, this.pageIndex, this.pageSize))
    }


    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is SearchUiState.LoadSimpleVideoSuccess -> {
                    mVideoList.clear()
                    mVideoList.addAll(it.list)
                    mVideoListAdapter.notifyDataSetChanged()

                    //判断搜索有数据就缓存一下关键词
                    if (it.list.isNotEmpty() && tempSearchKeyword.isNotEmpty()){
                        //之前搜索过，先清理掉
                        if(mHistoryList.indexOf(tempSearchKeyword) > -1){
                            mHistoryList.remove(tempSearchKeyword)
                        }
                        //在集合第一个位置插入数据
                        mHistoryList.add(0, tempSearchKeyword)

                        tempSearchKeyword = ""
                        mHistoryListAdapter.notifyDataSetChanged()
                    }
                }
                is SearchUiState.LoadSimpleVideoFail -> showToastMsg("没有搜索到您想要的视频内容！")
                else -> {}
            }
        }
    }
}